<template>
  <div>
    <common-dialog :title="title" ref="dialog" width="850px" :inDialog="inDialog" :before-save="onBeforeSave"
      @closed="onClosed" @close="onClose" @close-saved="$emit('close-saved')">
      <common-form ref="form" :data="data" :rules="rules">
        <el-divider>菜单信息</el-divider>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="data.name" placeholder="填写菜单名称"></el-input>
        </el-form-item>
        <el-form-item label="路径值" prop="path">
          <el-input v-model="data.path" placeholder="填写路径值" style="width:200px"></el-input>
          <span class="c-text-grey c-text-xs c-mg-l-5p">* 会与该菜单的所有上级菜单的路径值拼接成完整路径</span>
        </el-form-item>
        <el-form-item label="排序值" prop="order">
          <el-input-number v-model="data.order" controls-position="right"></el-input-number>
          <span class="c-text-grey c-text-xs c-mg-l-5p">* 值越小排得越前</span>
        </el-form-item>
        <el-form-item label="上级菜单" prop="parentId">
          <input-select :options="parentMenuOptions" v-model="data.parentId" @click="showParentMenuDialog" />
        </el-form-item>
        <el-form-item label="多开页面" prop="canMultipleOpen">
          <el-switch v-model="data.canMultipleOpen"></el-switch>
          <span class="c-text-grey c-text-xs c-mg-l-5p">* 在页面标签模式下，页面是否会根据参数的不同打开多个页面</span>
        </el-form-item>
        <el-form-item label="子页面" prop="isPage">
          <el-switch v-model="data.isPage"></el-switch>
          <span class="c-text-grey c-text-xs c-mg-l-5p">* 是否为子页面，不显示在菜单列表中，仅能在底层菜单下级创建，权限验证由上级菜单决定</span>
        </el-form-item>
        <div v-show="!data.isPage">
          <el-form-item label="菜单图标" prop="icon">
            <el-input v-model="data.icon" style="width:200px" placeholder="填写图标类名"></el-input>

            <span class="c-text-grey c-text-xs c-mg-l-5p">
              * 图标预览：
              <i :class="data.icon || $store.state.sys.config.MENU_DEFAULT_ICON"></i>
            </span>
          </el-form-item>
          <el-form-item label="菜单接口">
            <common-list ref="apiList" :show-query="false" :page="false" :border="false" :data="data.apis"
              show-checkbox>
              <template #toolbar-left>
                <el-button type="primary" @click="showApiDialog()">添加</el-button>
                <el-button @click="removeApis()">删除</el-button>
                <span class="c-text-grey c-text-xs c-mg-l-10p">* 拥有菜单的访问权限，就拥有以下接口访问权限。</span>
              </template>
              <template #column>
                <el-table-column label="接口名称" prop="name" min-width="100" show-overflow-tooltip></el-table-column>
                <el-table-column label="接口路径" prop="path" min-width="150" show-overflow-tooltip></el-table-column>
                <!-- <el-table-column label="操作" width="60" align="center">
                  <template v-slot="{ row }">
                    <el-button type="text" icon="el-icon-delete" @click="removeApis(row)" />
                  </template>
                </el-table-column> -->
              </template>
            </common-list>
            <!-- <api-edit-list ref="apiEditList"></api-edit-list> -->
          </el-form-item>
          <el-form-item label="菜单权限">
            <common-list ref="permissionList" show-checkbox :show-query="false" :page="false" :border="false"
              :data="data.permissions">
              <template #toolbar-left>
                <el-button type="primary" @click="showPermissionDialog">添加</el-button>
                <el-button @click="removePermissions()">删除</el-button>
                <span class="c-text-grey c-text-xs c-mg-l-10p">* 拥有菜单的对应权限，就拥有对应权限接口访问权限。</span>
              </template>
              <template #column>
                <el-table-column label="权限值" prop="code" width="100"></el-table-column>
                <el-table-column label="权限名" prop="name" width="100"></el-table-column>
                <el-table-column label="排序" prop="order" align="center" width="80"></el-table-column>
                <el-table-column label="接口">
                  <template #default="{ row }">
                    <div v-for="a in  row.apis" :key="a.apiId">
                      {{ a.name }} [{{ a.path }}]
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="60" align="center">
                  <template v-slot="{ row }">
                    <el-button type="text" icon="el-icon-edit" @click="showEditPermission(row)" />
                  </template>
                </el-table-column>
              </template>
            </common-list>
          </el-form-item>
        </div>
      </common-form>
      <template #footer>
        <el-button type="primary" @click="save" :loading="isSaveLoading" :disabled="isSaveDisabled">保存</el-button>
      </template>
      <menu-dialog ref="menuDialog" in-dialog :select-leaf="data.isPage" title="选择上级菜单" selectable @selected="setParent" />
      <common-dialog in-dialog width="600px" title="菜单权限" ref="permissionDialog" @closed="onPermissionDialogClosed">
        <common-form ref="permissionForm" :data="permissionData" :rules="permissionDataRules">
          <el-divider>权限信息</el-divider>
          <el-form-item label="权限值" prop="code">
            <el-input placeholder="权限值，同一个菜单里必须唯一" v-model="permissionData.code" />
          </el-form-item>
          <el-form-item label="权限名称" prop="name">
            <el-input placeholder="权限名称，尽量不超出4个字符" v-model="permissionData.name" />
          </el-form-item>
          <el-form-item label="排序值" prop="order">
            <el-input-number v-model="permissionData.order" controls-position="right"></el-input-number>
            <span class="c-text-grey c-text-xs c-mg-l-5p">* 值越小排得越前</span>
          </el-form-item>
          <el-form-item label="权限接口">
            <common-list ref="permissionApiList" show-checkbox :show-query="false" :page="false" :border="false"
              :data="permissionData.apis">
              <template #toolbar-left>
                <el-button type="primary" @click="showApiDialog('permissionApi')">添加</el-button>
                <el-button @click="removePermissionApis()">删除</el-button>
              </template>
              <template #column>
                <el-table-column label="接口名称" prop="name" min-width="100" show-overflow-tooltip></el-table-column>
                <el-table-column label="接口路径" prop="path" min-width="150" show-overflow-tooltip></el-table-column>
                <!-- <el-table-column label="操作" width="60" align="center">
                  <template v-slot="{ row }">
                    <el-button type="text" icon="el-icon-delete" @click="removePermissionApis(row)" />
                  </template>
                </el-table-column> -->
              </template>
            </common-list>
          </el-form-item>
        </common-form>
        <template #footer>
          <el-button type="primary" @click="savePermission">保存</el-button>
        </template>
      </common-dialog>
      <api-dialog ref="apiDialog" in-dialog multiple selectable @select-multiple="onApiDialogSelected"></api-dialog>
    </common-dialog>
  </div>
</template>
<script>
import commonDialog from "@/components/common/dialog";
import commonList from "@/components/common/list";
import commonForm from "@/components/common/form";
import editDialogMixin from "@/mixins/editDialog";
import api from "@/api/sys/menu";
import menuDialog from "./listDialog";
import apiEditList from "./apiEditList";
import apiDialog from "@/components/sys/api/listDialog";

export default {
  mixins: [editDialogMixin],
  components: { commonDialog, menuDialog, apiEditList, commonList, commonForm, apiDialog },
  data() {
    return {
      data: {
        id: 0,
        parentId: null,
        name: "",
        path: "",
        icon: "",
        parentName: "",
        canMultipleOpen: false,
        isPage: false,
        order: 99,
        hasRead: false,
        hasWrite: false,
        hasReview: false,
        apis: [],
        permissions: []
      },
      title: "",
      apiDialogType: "api",
      permissionData: {
        code: "",
        name: "",
        apis: [],
        order: 99
      },
      editPermissionData: null,
      permissionDataRules: {
        code: [{ required: true, message: "请填写权限值" }],
        name: [{ required: true, message: "请填写权限名称" }],
      },
      unit: "菜单",
      api,
      parentMenuOptions: [],
      rules: {
        name: [{ required: true, message: "请填写菜单名称" }],
        path: [{ required: true, message: "请填写菜单路径值" }],
        order: [{ required: true, message: "请填写菜单排序值" }]
      },
      isSaveLoading: false,
      isSaveDisabled: false,
      isSaved: false
    };
  },
  methods: {
    async getData(id) {
      this.$refs.dialog.loading(true);
      this.isSaveDisabled = true;
      let res = await api.getEditById(id)
      this.data = res.data;
      this.setParent({
        id: this.data.parentId,
        name: this.data.parentName
      })
      this.$refs.dialog.loading(false);
      this.isSaveDisabled = false;
    },
    async showCreate(row) {
      this.title = "创建菜单";
      await this.$refs.dialog.show()
      this.setParent(row);
    },
    async showEditById(id) {
      this.title = "编辑菜单";
      this.$refs.dialog.loading(true);
      await this.$refs.dialog.show();
      await this.getData(id);
    },
    //
    async showParentMenuDialog() {
      await this.$refs.menuDialog.showData({ notId: this.data.id, isPage: false })
      // .then(that => {
      //   that.$refs.list.getData({ notId: this.data.id, isPage: false });
      // });
    },
    setParent(row) {
      if (!row) {
        return;
      }
      this.data.parentId = row.id;
      this.parentMenuOptions = [{ id: row.id, name: row.name }];
    },
    onBeforeSave() {
      let menuApiIds = this.$refs.apiEditList.listData.map(item => {
        return item.apiId
      });
      this.data.apiIds = menuApiIds;
      return true;
    },
    onClosed() {
      this.$refs.form.reset();
      this.title = "";
      this.isSaved = false;
    },
    onClose() {
      if (this.isSaved) {
        this.$emit("close-saved");
      }
    },
    //保存菜单
    async save() {
      let valid = this.$refs.form.validate();
      if (!valid) {
        return;
      }
      this.$refs.dialog.loading(true);
      this.isSaveLoading = true;
      let postData = {
        ...this.data,
        apis: undefined,
        apiIds: this.data.apis.map(i => i.id),
        permissions: this.data.permissions.map(i => {
          return {
            code: i.code,
            name: i.name,
            order: i.order,
            apiIds: i.apis.map(i2 => i2.id)
          }
        })
      }
      let res = await api.save(postData);
      this.$refs.dialog.loading(false);
      this.isSaveLoading = false;
      if (res.code != 0) {
        return;
      }
      this.data.id = res.data;
      this.isSaved = true;
      this.$message.success("保存成功");
    },
    //显示接口窗口
    showApiDialog(type = "api") {
      this.apiDialogType = type;
      let apiIds = null;
      if (type == "api") {
        apiIds = this.data.apis.map(i => i.id);

      } else if (type == "permissionApi") {
        apiIds = this.permissionData.apis.map(i => i.id);
      }
      this.$refs.apiDialog.showData({
        notIds: apiIds
      });
    },
    //接口窗口选择后事件
    onApiDialogSelected(rows) {
      for (let item of rows) {
        let apis;
        if (this.apiDialogType == "api") {
          apis = this.data.apis
        } else if (this.apiDialogType == "permissionApi") {
          apis = this.permissionData.apis;
        }
        apis.push({
          id: item.id,
          name: item.name,
          path: item.path
        });
      }
    },
    //删除菜单接口
    removeApis(rows) {
      rows = rows || this.$refs.apiList.getCheckedRows();
      this.$refs.apiList.remove(rows);
    },
    //删除菜单接口
    removePermissions(rows) {
      rows = rows || this.$refs.permissionList.getCheckedRows();
      this.$refs.permissionList.remove(rows);
    },
    removePermissionApis(rows) {
      rows = rows || this.$refs.permissionApiList.getCheckedRows();
      this.$refs.permissionApiList.remove(rows);
    },
    onPermissionDialogClosed() {
      this.$refs.permissionForm.reset();
    },
    //添加菜单权限
    showPermissionDialog() {
      this.$refs.permissionDialog.show();
    },
    //显示权限编辑窗口
    async showEditPermission(row) {
      this.editPermissionData = row;
      await this.$refs.permissionDialog.show();
      this.$refs.permissionForm.setData(row);
    },
    //保存权限
    async savePermission() {
      let valid = await this.$refs.permissionForm.validate();
      if (!valid) {
        return;
      }
      let data = {
        code: this.permissionData.code,
        name: this.permissionData.name,
        order: this.permissionData.order,
        apis: this.permissionData.apis.map(i => ({
          id: i.id,
          name: i.name,
          path: i.path
        }))
      }
      if (this.editPermissionData) {
        this.editPermissionData.code = data.code;
        this.editPermissionData.name = data.name;
        this.editPermissionData.order = data.order;
        this.editPermissionData.apis = data.apis;
        this.editPermissionData = null;
      } else {
        this.data.permissions.push(data);
      }
      this.$refs.permissionDialog.close();
    }
  }
};
</script>